<template>
  <div class="admin">
    <el-input
        class="input"
        placeholder="请输入昵称"
        v-model="keywords"
        clearable>
    </el-input>
    <el-button @click="searchAdmin" icon="el-icon-search" type="primary">搜索</el-button>
    <el-button @click="addAdmin" icon="el-icon-plus" type="primary">添加管理员</el-button>
    <el-button @click="deleteAdminBatch" icon="el-icon-delete" type="danger" :disabled="adminIds.length === 0">批量删除</el-button>
    <el-table v-loading="loading" :data="tableData" class="table" @selection-change="changeSelection">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
                prop="avatarUrl"
                label="头像"
                width="150">
          <template slot-scope="scope">
            <el-avatar :src="scope.row.avatarUrl"></el-avatar>
          </template>
        </el-table-column>
      <el-table-column
          prop="username"
          label="账号"
          width="150">
      </el-table-column>
      <el-table-column
          prop="nickName"
          label="昵称"
          width="150">
      </el-table-column>
      <el-table-column
          prop="gender"
          label="性别"
          width="150">
        <template slot-scope="scope">{{ scope.row.gender ? '男': '女' }}</template>
      </el-table-column>
      <el-table-column
          prop="phoneNumber"
          label="手机号"
          width="150">
      </el-table-column>
      <el-table-column
          prop="enabled"
          label="账号状态"
          width="150">
          <template slot-scope="scope">{{ scope.row.enabled ? '可用': '禁用' }}</template>
      </el-table-column>
      <el-table-column
          prop="roles"
          label="角色"
          width="300">
         <template slot-scope="scope">{{ getRoles(scope.row.roles) }}</template>
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="300">
        <template slot-scope="scope">
          <el-button @click="editAdmin(scope.row)" size="small" type="primary" icon="el-icon-edit">编辑</el-button>
          <el-popconfirm class="confirm" title="确定删除？" @confirm="deleteAdmin(scope.row)">
            <el-button  size="small" slot="reference" type="danger" icon="el-icon-delete">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @current-change="changePage"
        class="page"
        background
        layout="prev, pager, next"
        :page-size="pageSize"
        :total="total">
    </el-pagination>
    <el-dialog :title="adminFormTitle" :visible="showAdminForm"  @close="closeAdminForm">
      <el-form :model="adminForm" label-width="100px" ref="adminForm" :rules="adminRules" >
        <el-form-item prop="avatarUrl" label="头像" style="display: flex; align-items: center">
          <el-upload
            action=""
            class="avatar-uploader"
            accept=".png,.jpg"
            :http-request="uploadAvatar"
            :show-file-list="false">
            <el-image v-if="adminForm.avatarUrl.length > 0" :src="adminForm.avatarUrl"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item prop="username" label="账号" >
          <el-input v-model="adminForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="adminForm.password" type="password" :disabled="adminFormTitle === '编辑管理员'"></el-input>
        </el-form-item>
        <el-form-item prop="nickName" label="昵称" >
          <el-input v-model="adminForm.nickName"></el-input>
        </el-form-item>
        <el-form-item prop="gender" label="性别">
          <el-radio-group v-model="adminForm.gender">
            <el-radio :label="true">男</el-radio>
            <el-radio :label="false">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="phoneNumber" label="手机号">
          <el-input v-model="adminForm.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item prop="enabled" label="账号状态">
          <el-radio-group v-model="adminForm.enabled">
            <el-radio :label="true">可用</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="roleIds" label="角色">
          <el-transfer v-model="adminForm.roleIds" :data="roleList" :props="{key: 'id', label: 'title'}" :titles="['全部角色', '已选角色']"></el-transfer>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="closeAdminForm">取消</el-button>
        <el-button type="primary" @click="submitAdminForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Admin",
  data () {
    return {
      loading: false,
      tableData: [],
      keywords: '',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      adminIds: [],
      adminForm: {
        username: '',
        password: '',
        nickName: '',
        avatarUrl: '',
        gender: true,
        phoneNumber: '',
        enabled: true,
        roleIds: []
      },
      adminRules: {
        username: [{ required: true, message: '必填', trigger: 'blur' }],
        password: [{ required: true, message: '必填', trigger: 'blur' }],
        nickName: [{ required: true, message: '必填', trigger: 'blur' }],
        avatarUrl: [{ required: true, message: '必填', trigger: 'blur' }],
        gender: [{ required: true, message: '必填', trigger: 'blur' }],
        phoneNumber: [{ required: true, message: '必填', trigger: 'blur' }],
        enabled: [{ required: true, message: '必填', trigger: 'blur' }],
        roleIds: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      adminFormTitle: '',
      showAdminForm: false,
      roleList: []
    }
  },
  methods:{
    uploadAvatar (param) {
      let formData = new FormData()
      formData.append('file', param.file)
      formData.append('code', 1)
      this.$axios({
        url: '/auth/upload',
        method: 'post',
        data: formData,
        headers: {
          "Content-Type": "multipart/form-data"
        }
      }).then(res => {
        if (res.code === 200) {
          this.adminForm.avatarUrl = window.uploadUrl + res.data
        }
      })

    },
    closeAdminForm () {
      this.showAdminForm = false
      this.adminForm = {
        username: '',
        password: '',
        nickName: '',
        avatarUrl: '',
        gender: true,
        phoneNumber: '',
        enabled: true,
        roleIds: []
      }
      this.roleList = []
    },
    submitAdminForm: function () {
      const adminBo = this.adminForm
      if (this.adminForm.id) {
        this.$refs.adminForm.validate(valid => {
          if (valid) {
            this.$axios.put(`/admin/${this.adminForm.id}`, adminBo).then(res => {
              if (res.code === 200) {
                this.closeAdminForm()
                this.pageNum = 1
                this.loadTableData()
              }
            })
          }
        })
      } else {
        this.$refs.adminForm.validate(valid => {
          if (valid) {
            this.$axios.post('/admin', adminBo).then(res => {
              if (res.code === 200) {
                this.closeAdminForm()
                this.pageNum = 1
                this.loadTableData()
              }
            })
          }
        })
      }
    },
    loadTableData () {
      this.loading = true
      this.$axios.get(`/admin?keywords=${this.keywords}&&pageNum=${this.pageNum}&&pageSize=${this.pageSize}`).then(res => {
        if (res.code === 200) {
          this.loading = false
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },
    addAdmin () {
      this.loadRoleList()
      this.adminFormTitle = '添加管理员'
      this.showAdminForm = true
    },
    loadRoleList () {
      this.$axios.get('/admin/role').then(res => {
        this.roleList = res.data
      })
    },
    editAdmin (row) {
      this.adminForm = {
        id: row.id,
        username: row.username,
        password: 'canteen',
        nickName: row.nickName,
        avatarUrl: row.avatarUrl,
        gender: row.gender,
        phoneNumber: row.phoneNumber,
        enabled: row.enabled,
        roleIds: row.roles.map(role => {
          return role.id
        })
      }
      this.loadRoleList()
      this.adminFormTitle = '编辑管理员'
      this.showAdminForm = true
    },
    deleteAdmin(row) {
      this.$axios.delete(`/admin/${row.id}`).then(res => {
        if (res.code === 200) {
          this.searchAdmin()
        }
      })
    },
    deleteAdminBatch () {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete('/admin/batch', {
          data: this.adminIds
        }).then(res => {
          if (res.code === 200) {
            this.searchAdmin()
          }
        })
      })
    },
    searchAdmin() {
      this.pageNum = 1
      this.loadTableData()
    },
    changePage (pageNum) {
      this.pageNum = pageNum
      this.loadTableData()
    },
    changeSelection (rows) {
      this.adminIds = []
      for (const row of rows) {
        this.adminIds.push(row.id)
      }
    },
    getRoles (roles) {
      let roleArray = []
      for (const role of roles) {
        roleArray.push(role.title)
      }
      return roleArray.join()
    },

  },
  computed: {
  },
  mounted() {
    this.loadTableData()
  }
}
</script>

<style lang="scss" scoped>
  .admin {
    width: 100%;
    height: 100%;
    .input {
      width: 300px;
      margin: 0 20px 0 0;
    }
    .table {
      width: 100%;
      margin-top: 20px;
    }
    .confirm {
      margin-left: 20px;
    }
    .page {
      margin: 20px 0;
    }
    .avatar-uploader{
      border: 1px dashed #d9d9d9;
      border-radius: 100%;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      width: 70px;
      height: 70px;
      &:hover {
        border-color: #409EFF;
      }
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 70px;
      height: 70px;
      line-height: 70px;
      text-align: center;
    }
  }
</style>
